"""
实体提取处理器插件
从文本中提取实体的处理器插件
"""

from typing import List, Dict, Any
from src.services.plugin_system.processor_plugin import ProcessorPlugin


class EntityExtractorProcessor(ProcessorPlugin):
    """实体提取处理器插件"""
    
    async def initialize(self) -> bool:
        """初始化插件"""
        try:
            # 可以在这里加载NLP模型等
            self.logger.info("实体提取处理器插件初始化成功")
            return True
        except Exception as e:
            self.logger.error(f"实体提取处理器插件初始化失败: {e}")
            return False
    
    async def process(self, data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """处理数据，提取实体"""
        processed_data = []
        for item in data:
            # 这里可以使用NLP技术提取实体
            # 简化示例，仅提取标题中的关键词
            entities = []
            title = item.get("title", "")
            domain = item.get("domain", "general")  # 新增领域信息
            
            if title:
                # 简单的关键词提取
                words = title.split()
                # 根据不同领域使用不同的实体类型
                if domain == "medical":
                    entities = [{"name": word, "type": "medical_term"} for word in words if len(word) > 3]
                elif domain == "financial":
                    entities = [{"name": word, "type": "financial_term"} for word in words if len(word) > 3]
                else:
                    entities = [{"name": word, "type": "keyword"} for word in words if len(word) > 3]
            
            item["entities"] = entities
            item["domain"] = domain  # 保留领域信息
            processed_data.append(item)
        
        return processed_data
    
    def entity_alignment(self, entities: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        实体对齐功能，将不同来源但表示相同概念的实体进行合并
        
        Args:
            entities: 实体列表
            
        Returns:
            对齐后的实体列表
        """
        # 实现实体对齐逻辑
        # 这里可以使用字符串相似度、嵌入相似度等方法
        aligned_entities = []
        entity_groups = {}  # 用于分组相似实体
        
        for entity in entities:
            entity_name = entity["name"]
            # 简化的对齐逻辑：基于字符串相似度
            matched = False
            for group_name, group_entities in entity_groups.items():
                # 检查是否与现有组中的实体相似
                if self._is_similar(entity_name, group_name):
                    group_entities.append(entity)
                    matched = True
                    break
            
            if not matched:
                entity_groups[entity_name] = [entity]
        
        # 为每个组创建一个代表实体
        for group_name, group_entities in entity_groups.items():
            # 选择最具代表性的实体作为组的代表
            representative = group_entities[0]
            representative["aliases"] = [e["name"] for e in group_entities]
            aligned_entities.append(representative)
        
        return aligned_entities
    
    def _is_similar(self, str1: str, str2: str, threshold: float = 0.8) -> bool:
        """
        判断两个字符串是否相似
        
        Args:
            str1: 字符串1
            str2: 字符串2
            threshold: 相似度阈值
            
        Returns:
            是否相似
        """
        # 简单实现：基于编辑距离的相似度
        from difflib import SequenceMatcher
        similarity = SequenceMatcher(None, str1.lower(), str2.lower()).ratio()
        return similarity >= threshold
    
    async def execute(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """执行插件功能"""
        input_data = data.get("data", [])
        result = await self.process(input_data)
        return {"data": result}